package com.zoho.daliansheng.service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.zoho.daliansheng.common.U8SystemRecord;
import com.zoho.daliansheng.common.ZohoRecord;
import com.zoho.daliansheng.config.CRMPathConfig;
import com.zoho.daliansheng.config.DatasourceEnum;
import com.zoho.daliansheng.config.U8SystemPathConfig;
import com.zoho.daliansheng.dlcr.DlcrU8WebService;
import com.zoho.daliansheng.dlcr.DlcrU8WebServiceSoap;
import com.zoho.daliansheng.dlcr.QueryRetInfo;
import com.zoho.daliansheng.utils.CrmApiUtil;
import com.zoho.daliansheng.utils.getCrmFieldUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

@Slf4j
@Service
public class CurrentStockDateServiceImpl implements CurrentStockDateService {

    ZohoRecord zohoRecord;

    U8SystemRecord u8SystemRecord;

    U8SystemPathConfig u8SystemPathConfig;

    CRMPathConfig crmPathConfig;

    public CurrentStockDateServiceImpl(ZohoRecord zohoRecord, U8SystemRecord u8SystemRecord, U8SystemPathConfig u8SystemPathConfig, CRMPathConfig crmPathConfig) {
        this.zohoRecord = zohoRecord;
        this.u8SystemRecord = u8SystemRecord;
        this.u8SystemPathConfig = u8SystemPathConfig;
        this.crmPathConfig = crmPathConfig;
    }

    @Override
    public void synCurrentStockDate() {
        /*
         * 1 获取CRM 现存量 模块数据
         */
        List<String> fieldList = getCrmFieldUtil.getCurrentStockFieldList();
        List<JSONObject> crmData = CrmApiUtil.getModuleData(zohoRecord.getAccessToken(), crmPathConfig.getCurrentStockModuleName(), fieldList);
        System.out.println("crmData.size() = " + crmData.size());

        /*
         * 2 同步ERP 现存量 入库日期
         */
        try {
//            synU8Data(crmData, DatasourceEnum.GONG_CHANG.getWebServiceUrl(), DatasourceEnum.GONG_CHANG.getAccountCode(), DatasourceEnum.GONG_CHANG.getCompanyName());
            synU8Data(crmData, DatasourceEnum.SU_ZHOU.getWebServiceUrl(), DatasourceEnum.SU_ZHOU.getAccountCode(), DatasourceEnum.SU_ZHOU.getCompanyName());
            synU8Data(crmData, DatasourceEnum.CHANG_ZHOU.getWebServiceUrl(), DatasourceEnum.CHANG_ZHOU.getAccountCode(), DatasourceEnum.CHANG_ZHOU.getCompanyName());
            synU8Data(crmData, DatasourceEnum.DA_LIAN.getWebServiceUrl(), DatasourceEnum.DA_LIAN.getAccountCode(), DatasourceEnum.DA_LIAN.getCompanyName());
            synU8Data(crmData, DatasourceEnum.XIN_CAI_LIAO.getWebServiceUrl(), DatasourceEnum.XIN_CAI_LIAO.getAccountCode(), DatasourceEnum.XIN_CAI_LIAO.getCompanyName());
        } catch (Exception e) {
            e.printStackTrace();
        }

    }


    private void synU8Data(List<JSONObject> crmData, String webServiceUrl, String accountCode, String companyName ) throws MalformedURLException {

        String synModuleName = crmPathConfig.getCurrentStockDateModuleName(); // 要同步的模块名称

        //crmData = allCrmData;
        // 1 过滤CRM数据，只保留单一账套
        crmData = crmData.stream().filter(object -> Objects.nonNull(object.getString("AffiliatedCompany")) && object.getString("AffiliatedCompany").equals(companyName)).collect(Collectors.toList());

        // 2 模块最大版本号
        Map<String, String> map = CrmApiUtil.getMaxVersion(zohoRecord.getAccessToken(), synModuleName, accountCode);
        String versionCrmId = map.get("id");
        int maxVersion = Integer.parseInt(map.get("maxVersion"));

        // 3 获取ERP数据
        DlcrU8WebService webService = new DlcrU8WebService(new URL(webServiceUrl));
        DlcrU8WebServiceSoap api = webService.getDlcrU8WebServiceSoap();
        QueryRetInfo queryRetInfo = api.queryLatestStockInRecords(maxVersion);
        int queryMaxVersion = queryRetInfo.getMaxVersion();
        JSONArray jsonArray = JSONArray.parseArray(queryRetInfo.getJson());
        if (jsonArray.size() > 0) {

            // 4 比较数据
            List<JSONObject> updateList = new ArrayList<>();
            List<JSONObject> batchCurrentStock = jsonArray.toJavaList(JSONObject.class);

            for (JSONObject erpData : batchCurrentStock) {
                String autoid = erpData.getString("id"); // erp id
                List<JSONObject> searchList = crmData.stream().filter(object -> Objects.nonNull(object.getString("autoid")) && object.getString("autoid").equals(autoid) &&
                        object.getString("AffiliatedCompany").equals(companyName)
                ).collect(Collectors.toList());

                if (searchList.size() > 0) {
                    JSONObject updateData = new JSONObject();
                    JSONObject jsonObject = searchList.get(0);
                    String crmId = jsonObject.getString("id");
                    updateData.put("id", crmId);
                    if(StringUtils.isNotBlank(erpData.getString("dnverifytime"))){
                        updateData.put("Warehousing_date", erpData.getString("dnverifytime").substring(0, 10)); // 入库日期
                        updateList.add(updateData);
                    }
                }
            }

            // 5 字段映射
            log.info("同步【" + companyName + "】");
            System.out.println("crm_updateList.size() = " + updateList.size());

            // 6 批量操作
            CrmApiUtil.batchUpdateDataByList(zohoRecord.getAccessToken(), updateList, crmPathConfig.getCurrentStockModuleName());

            // 7 最大版本号回传
            if (queryMaxVersion != maxVersion) {
                CrmApiUtil.saveMaxVersion(zohoRecord.getAccessToken(), versionCrmId, queryMaxVersion, crmPathConfig.getMaxVersionModuleName());
            }
        }

    }


}
